package org.example.buysystem.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.buysystem.constants.Constants;
import org.example.buysystem.entity.Good;
import org.example.buysystem.entity.Order;
import org.example.buysystem.entity.OrderGoods;
import org.example.buysystem.entity.OrderItem;
import org.example.buysystem.exception.ServiceException;
import org.example.buysystem.mapper.GoodMapper;
import org.example.buysystem.mapper.OrderGoodsMapper;
import org.example.buysystem.mapper.OrderMapper;
import org.example.buysystem.mapper.StandardMapper;
import org.example.buysystem.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static org.example.buysystem.constants.RedisConstants.GOOD_TOKEN_KEY;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> {

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private CartService cartService;

    @Autowired
    private GoodMapper goodMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StandardMapper standardMapper;

    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    public String saveOrder(Order order) {
        if (order == null) {
            throw new RuntimeException("订单数据为空");
        }

        if (order.getUserId() == null) {
            throw new RuntimeException("用户ID不能为空");
        }

        String orderNo = DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomNumbers(6);
        order.setOrderNo(orderNo);
        order.setCreateTime(DateUtil.now());

        if (orderMapper == null) {
            throw new RuntimeException("orderMapper 注入失败");
        }
        orderMapper.insert(order);

        String goods = order.getGoods();
        if (goods != null && !goods.isEmpty()) {
            List<OrderItem> orderItems = JSON.parseArray(goods, OrderItem.class);
            for (OrderItem orderItem : orderItems) {
                if (orderItem == null) continue;
                OrderGoods orderGoods = new OrderGoods();
                orderGoods.setOrderId(order.getId());
                orderGoods.setGoodId(orderItem.getId());
                orderGoods.setStandard(orderItem.getStandard());
                orderGoods.setCount(orderItem.getNum());

                if (orderGoodsMapper == null) {
                    throw new RuntimeException("orderGoodsMapper 注入失败");
                }
                orderGoodsMapper.insert(orderGoods);
            }
        }

        if (cartService != null && order.getCartId() != null) {
            cartService.removeById(order.getCartId());
        }

        return orderNo;
    }





    public List<Map<String,Object>>  findByUserId(int userid) {

        return orderMapper.findByUserId(userid);
    }

    public List<String> findByTotalOrderNo(String totalorderNo) {
        List<String> orderNos=orderMapper.findByTotalOrderNo(totalorderNo);
        return orderNos;
    }

    public void paid(String orderNo) {
        LambdaUpdateWrapper<Order> orderLambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        orderLambdaUpdateWrapper.eq(Order::getOrderNo,orderNo).set(Order::getState,"已发货");
        update(orderLambdaUpdateWrapper);

    }

    public void payOrder(String orderNo) {
        //更改状态为待付款
        orderMapper.payOrder(orderNo);
        //给对应商品的规格减库存
        Map<String,Object> orderMap=orderMapper.selectByOrderNo(orderNo);
        int count=(int)orderMap.get("count");
        Object goodIDobj=orderMap.get("goodId");
        Long goodId=null;
        //判断goodId是否Long
        if (goodIDobj instanceof Long){
            goodId=(Long)goodIDobj;
        }else if (goodIDobj!=null){
            try {
                goodId=Long.parseLong(goodIDobj.toString());
            } catch (NumberFormatException e) {
                throw new ServiceException(Constants.CODE_500,"商品ID不正确");
            }
        }

        if (goodId==null){
            throw new ServiceException(Constants.CODE_500,"商品ID不存在");
        }

        String standard=(String) orderMap.get("standard");
        //获取库存信息
        int store = standardMapper.getStore(goodId,standard);
        //库存不足
        if (store<count){
            throw new ServiceException(Constants.CODE_500,"库存不足");
        }

        //减库存
        standardMapper.deductStore(goodId,standard,store-count);

        //给对应商品增加销售额和销量
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper=new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(Order::getOrderNo,orderNo);
        Order one=getOne(orderLambdaQueryWrapper);
        BigDecimal totalPrice=one.getTotalPrice();
        goodMapper.saleGood(goodId,count,totalPrice);

        //redis增加销量
        String redisKey=GOOD_TOKEN_KEY +goodId;
        ValueOperations<String , Good> valueOperations=redisTemplate.opsForValue();

        Good good=valueOperations.get(redisKey);
        if (!ObjectUtils.isEmpty(good)){
            good.setSales(good.getSales()+count);
            valueOperations.set(redisKey, good);
        }
    }

    public boolean receivedOrder(String totalorderNo) {
        return orderMapper.receivedOrder(totalorderNo);

    }

    public Map<String, Object> selectByOrderNo(String orderNo) {
        return orderMapper.selectByOrderNo(orderNo);
    }

    public List<String> selectByOrderNoTotal(String totalorderNo) {
        List<String> orderNos=orderMapper.selectByOrderNoTotal(totalorderNo);
        return orderNos;
    }
}
